<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-form :inline="true">
        <el-form-item label=" 机构  "  prop="departmentId">
          <el-select v-model="listQuery.departmentId" @change="deptChange" clearable placeholder="请选择">
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="停车场">
          <el-select v-model="listQuery.parkId" placeholder="请选择" clearable style="width: 90px;">
            <el-option
              v-for="item in allParkList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
       <el-form-item label=" 出入口名称">
          <el-select ref="churu1" v-model="listQuery.portId" clearable
          remote
          v-loadMore="loadMore"
          :remote-method="remoteMethod"
          :loading="crloading"
          filterable  placeholder="请选择出入口">
            <el-option
              v-for="item in crparkList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态">
          <el-select v-model="listQuery.deviceStatus" placeholder="请选择" clearable>
            <el-option
              v-for="item in shebeiStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>

        <el-button
          v-hasPermi="['admin:railDevice:create']"
          class="filter-item"
          style="float:right"
          type="primary"
          icon="el-icon-plus"
          @click="startAdd">添加</el-button>
      </el-form>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row default-expand-all>
      <!-- <el-table-column align="center" label="出入口id" prop="id" /> -->
      <el-table-column type="expand">
        <template slot-scope="{row}">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-row v-for="(item1,index1) in row.portList" :key="index1" style="margin:0 15px;">
              <el-col :span="8" v-for="(item,index) in detailList"  :key="index">
                <el-form-item :label="item.label">
                  <span>{{ item1[item.value] }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="所属机构" prop="departmentName"/>
      <el-table-column align="center" label="停车场名称" prop="parkName"/>
      <el-table-column align="center" label="出入口" prop="portName" /> -->
      <el-table-column align="center" label="设备厂家" prop="manufacturerDesc" />
      <el-table-column align="center" label="设备类型" prop="deviceTypeDesc"/>
      <el-table-column align="center" label="设备标识" prop="deviceId"/>
      <el-table-column align="center" label="设备编码" prop="deviceCode" />
      <el-table-column align="center" label="是否控制道闸" prop="controlRailFlagDesc" ></el-table-column>
      <el-table-column align="center" label="设备状态" prop="deviceStatus" >
        <template slot-scope="{row}">
          <div :style="{color: row.deviceStatus == 2 ? 'green' : 'red'}">
            {{ row.deviceStatus == 2 ? '在线' : '离线' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" prop="createTime" />
      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['admin:railDevice:update']"
            type="primary"
            size="small"
            @click="startEditPassway(scope.row)">编辑</el-button>
          <el-button type="danger"
          v-hasPermi="['admin:railDevice:delete']"
          size="small"
          @click="deletePassway(scope.row.deviceTypeDesc, scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :close-on-click-modal="false" :title="dialogType == 1?'添加设备':'修改设备'" :visible.sync="dialogFormVisible" width="50%">
      <el-form ref="dialogForm"  :rules="formRules" :model="dialogForm" label-width="140px">
        <el-row>
          <el-col :span="12">
            <el-form-item label=" 设备厂家" prop="manufacturer">
              <el-select v-model="dialogForm.manufacturer" placeholder="请选择" :style="{'width':formWidth}">
                <el-option
                  v-for="item in changjiaLIst"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(item.value)"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=" 设备标识" prop="deviceId">
              <el-input v-model="dialogForm.deviceId" clearable class="filter-item" :style="{'width':formWidth}" placeholder="请输入设备标识"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=" 设备编码" prop="deviceCode">
              <el-input v-model="dialogForm.deviceCode" clearable class="filter-item" :style="{'width':formWidth}" placeholder="请输入设备编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=" 设备类型" prop="deviceType">
              <el-select v-model="dialogForm.deviceType" placeholder="请选择" :style="{'width':formWidth}">
                <el-option
                  v-for="item in deviceList"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(item.value)"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-for="(item,index) in dialogForm.portList" :key="index">
          <el-col :span="7">
            <el-form-item label=" 机构  " prop="departmentId"  label-width="80px">
              <el-select v-model="item.departmentId" placeholder="请选择" @change="(e)=>DepartmentChange(e,index)" :style="{'width':'100%'}">
                <el-option
                  v-for="item in departmentList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label=" 停车场  " prop="parkId" label-width="80px">
              <el-select v-model="item.parkId"  placeholder="请选择" @change="(e)=>parkChaneg(e,index)" :style="{'width':'100%'}">
                <el-option
                  v-for="item in item.parkList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label=" 关联出入口" prop="portId"  label-width="100px">
              <div class="flex_hcneter">
                <el-select ref="churu" @change="(e)=>rukouChange(e,index)" v-model="item.portId"
                filterable  placeholder="请选择关联出入口" class="flex_flex">
                  <el-option
                    v-for="item in item.popcrparkList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"/>
                </el-select>
                <div style="margin-left:3%;">
                  <el-button type="primary" icon="el-icon-plus" @click="addList"></el-button>
                  <el-button type="danger" icon="el-icon-minus" @click="delList(index)" v-if="dialogForm.portList.length > 1"></el-button>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label=" 是否控制道闸" prop="controlRailFlag">
              <el-radio-group v-model="dialogForm.controlRailFlag" >
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label=" 屏显方式" v-if="dialogForm.manufacturer != 1 && dialogForm.manufacturer" prop="displayType">
              <el-select v-model="dialogForm.displayType" placeholder="请选择" :style="{'width':formWidth}">
                <el-option
                  v-for="item in displayList"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(item.value)"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer" align="center">
        <el-button @click="confirmEdit('dialogForm')">确定</el-button>
        <el-button @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { fetchList, railDeviceDetail, railDeviceAdd, railDeviceUpdate, railDeviceRemove } from '@/api/park/equipManage'
import { selectList,listAuthPassway,crlistAuthPort,listAuthPort } from '@/api/passway'
import { getDepartmentList,getListAuthPark } from '@/api/base'
import { getData, } from '@/api/system/dictionary'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import QRCode from 'qrcodejs2'

export default {
  name: 'EquipManage',
  components: { Pagination },
  data() {
    return {
      formWidth:'80%',//宽度
      detailList:[
        {label:'所属机构：',value:'departmentName'},
        {label:'停车场名称：',value:'parkName'},
        {label:'出入口：',value:'portName'},
      ],
      shebeiStatus:[],
      allParkList: [],//停车昌数据
      displayList:[],//屏显方式数据
      deviceList:[],//设备类型数据
      changjiaLIst:[],//厂家数据
      crlistQuery: {//出入口数据请求参数
        page: 1,
        pageSize: 10
      },
      crloading:false,//出入口下拉框加载
      crparkList:[],//出入口数据
      crTotal:0,//出入总数
      popcrlistQuery: {//弹窗关联出入口数据请求参数
        page: 1,
        pageSize: 10
      },
      popcrloading:false,//弹窗出入口下拉框加载
      popcrparkList:[],//弹窗关联出入口数据
      popcrTotal:0,//弹窗关联出入总数
      list: [],//表格数据
      total: 0,//表格总数
      listLoading: true,//表格加载
      listQuery: {//表格搜索参数
        page: 1,
        pageSize: 20
      },
      dialogTitle: '温馨提示',
      dialogFormVisible: false,//弹窗开启关闭
      dialogForm: {},//表单数据
      dialogType: 1,//表单类型
      name: '',
      formRules: {
        manufacturer: [{ required: true, message: '请选择设备厂家', validator: this.checkSelected, trigger: 'change' }],
        deviceId: [{ required: true, message: '请输入设备标识', trigger: 'blur' }],
        deviceCode: [{ required: true, message: '请输入设备编码', trigger: 'blur' }],
        // portId: [{ required: true, message: '请选择关联出入口', validator: this.checkSelected, trigger: 'change' }],
        deviceType: [{ required: true, message: '请选择设备类型', validator: this.checkSelected, trigger: 'change' }],
        controlRailFlag: [{ required: true, message: '请选择是否控制闸道', trigger: 'blur' }],
        displayType: [{ required: true, message: '请选择屏显方式', validator: this.checkSelected, trigger: 'change' }],
      },
      kazha: false,// 开闸请求冒泡
      parkList: [],//停车场数据
      departmentList: [],//机构数据
    }
  },
  created() {
    this.getDepartmentList()
    // this.crlistAuthPort(1)
    this.getList()
		this.getData()
		this.getData1()
		this.getData2()
		this.getData3()
  },
  methods: {
    addList(){//添加数组
      this.dialogForm.portList.push({})
    },
    delList(index){//删除数组
      this.dialogForm.portList.splice(index,1)
    },
    getDepartmentList(){//获取机构
      getDepartmentList().then(res => {
        this.departmentList = res.data || []
      })
    },
    async getListAuthPark(departmentId){//获取停车场
      let res = await getListAuthPark({departmentId,parkType:1})
      return res.data || []
    },
		async getData(){//设备状态
			let res = await getData('ERailDeviceStatus')
			let list = res.data || []
			this.shebeiStatus = [...list]
		},
		async getData1(){//设备状态
			let res = await getData('ERailScreenDisplayType')
			let list = res.data || []
			this.displayList = [...list]
		},
		async getData2(){//设备状态
			let res = await getData('ERailDeviceType')
			let list = res.data || []
			this.deviceList = [...list]
		},
		async getData3(){//设备状态
			let res = await getData('ERailDeviceManufacture')
			let list = res.data || []
			this.changjiaLIst = [...list]
		},
    async deptChange(e){//机构下拉选择
		  let listQuery = {...this.listQuery}
		  listQuery.parkId = ''
		  this.listQuery = {...listQuery}
      if(!e) return this.allParkList = []
      this.allParkList =await this.getListAuthPark(e)
		},
    async DepartmentChange(event,index){//机构下拉改变事件
      let dialogForm = {...this.dialogForm}
      dialogForm.portList[index].parkId = ''
      dialogForm.portList[index].portId = null
      dialogForm.portList[index].popcrparkList = []
      if(!event) {
        dialogForm.portList[index].parkList = []
        this.dialogForm = {...dialogForm}
        return 
      }
      dialogForm.portList[index].parkList = await this.getListAuthPark(event)
      this.dialogForm = {...dialogForm}
    },
    remoteMethod(e){//下拉远程搜索
      console.log('remoteMethod')
      this.crlistQuery.name = e
      this.crlistQuery.page = 1
      this.crlistAuthPort(1,1)
    },
    crlistAuthPort(types){
      if(types) this.crloading = true
      crlistAuthPort(this.crlistQuery).then(response => {
        if(this.crlistQuery.page == 1) this.crparkList = []
        let data = response.data
        let list = data.list || []
        this.crparkList = this.crparkList.concat(list)
        this.crTotal = data.total || 0
        console.log('this.crparkList',this.crparkList)
        console.log('this.crTotal',this.crTotal)
        if(types) this.crloading = false
      })
    },
    async parkChaneg(event,index){//部门下拉改变事件
      let dialogForm = {...this.dialogForm}
      dialogForm.portList[index].portId = null
      if(!event) {
        dialogForm.portList[index].popcrparkList = []
        this.dialogForm = {...dialogForm}
        return 
      }
      dialogForm.portList[index].popcrparkList = await this.crlistAuthPort1(event)
      this.dialogForm = {...dialogForm}
    },
    rukouChange(e,index){//弹窗出入口改变
      let dialogForm = {...this.dialogForm}
      dialogForm.portList[index].portId = e
      this.dialogForm = {...dialogForm}
    },
    async crlistAuthPort1(event){//根据停车id获取出入口
      let response = await listAuthPort(event)
      let list = response.data || []
      return list
    },
    //滚动加载更多方法
    loadMore(){
      console.log('loadMore加载');
      if(this.crparkList.length == this.crTotal) return
      this.crlistQuery.page+=1
      this.crlistAuthPort()
    },
    // 校验下拉框
    checkSelected(rule, value, callback) {
      if (!value) {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        let data = response.data || []
        this.list = data.list || []
        this.total = data.total || 0
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    deletePassway(name, parkId) {//删除
      this.$confirm(`您确定删除该设备`, '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        railDeviceRemove(parkId).then(response => {
          this.$message({
            message: '删除成功!',
            type: 'success'
          })
          this.getList()
        })
      })
    },
    startAdd() {//新增
      this.dialogForm = {
        portList:[{}]
      }
      this.dialogFormVisible = true
      this.dialogType = 1
      this.getDepartmentList()
    },
    confirmEdit(formName) {//提交
      console.log(this.dialogForm)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let form = {...this.dialogForm}
          if(form.manufacturer == 1) form.displayType = ''
          let portList = form.portList || []
          portList = portList.map(item=>item.portId)
          form.portIds = [...portList]
          if (this.dialogType === 1) {
            railDeviceAdd(form).then(response => {
              this.$message({
                message: '添加成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          } else {
            railDeviceUpdate(form).then(response => {
              this.$message({
                message: '修改成功!',
                type: 'success'
              })
              this.getList()
              this.dialogFormVisible = false
              this.dialogForm = {}
            })
          }
        }
      })
    },
    startEditPassway(row) {//修改
      railDeviceDetail(row.id).then(response => {
          let data = response.data || {}
          this.dialogFormVisible = true
          this.dialogType = 2
          let portList = data.portList || []
          portList.forEach((item,index)=>{
            this.getPostList(item,data,portList,index)
          })
          this.getDepartmentList()
      })


    },
    async getPostList(e,data,portList,index){//循环获取出入口和停车场数据
      portList[index].parkList = await this.getListAuthPark(e.departmentId)
      portList[index].popcrparkList = await this.crlistAuthPort1(e.parkId)
      if(index == portList.length - 1) {
        data.portList = [...portList]
        this.dialogForm = data
      }
    },
  }
}
</script>
<style scoped>
#qrcode{
  width: 250px;
  margin: 0 auto;
}
</style>
